import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;


public class PhotoApi {
AllegroDAO dao = new AllegroDAO();
	
public static void main(String[] args) {
	
	new PhotoApi();
}

public PhotoApi(){
	File dir;
	Integer count=1;
	ArrayList<AllegroDAO.UrlData> list = dao.getOfferPhotoUrl();
	for(AllegroDAO.UrlData data : list){
		try {
			 dir = new File("photo/"+data.id);
			dir.mkdir();
			saveImage(data.url , "photo/"+data.id+"/small.jpeg");
			saveImage(data.url.replace("128x96", "oryginal") , "photo/"+data.id+"/oryginal.jpeg");
			System.out.println("image saved" + count + " z " + list.size());
			count++;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

	
	public void saveImage(String imageUrl, String destinationFile) throws IOException {
		URL url = new URL(imageUrl);
		InputStream is = url.openStream();
		OutputStream os = new FileOutputStream(destinationFile);

		byte[] b = new byte[2048];
		int length;

		while ((length = is.read(b)) != -1) {
			os.write(b, 0, length);
		}

		is.close();
		os.close();
	}
}
